package com.haiheng.common.activity

import android.content.res.Resources
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.NavOptions
import androidx.navigation.fragment.NavHostFragment
import com.haiheng.common.constant.RourePage
import com.haiheng.common.utils.DatabaseHelper
import com.haiheng.library.common.R
import com.haiheng.library.log.LogUtils
import com.haiheng.library_base.activity.BaseActivity
import com.haiheng.library_base.http.HttpResponse
import com.haiheng.library_base.utils.WebViewManager
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.jessyan.autosize.AutoSizeCompat
import java.util.regex.Pattern

/**
 *
 * @Des:  路由类，方便模块之间调用
 * @Author: hwz
 * @Date:2022/4/15 0015
 * @Version: 1.0
 */
abstract class RouterActivity : BaseActivity() {

    private lateinit var navController: NavController
    private var exitTime = 0L

    /**
     * NavController的视图id
     */
    abstract fun controllerId(): Int

    /**
     * 导航方法，根据路由名跳转
     */
    abstract fun navigation(name : RourePage, bundle: Bundle? = null)

    abstract fun setTitleBgColor(color:Int)

    abstract fun isHasOperation():Boolean
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        /**
         * 单 Activity 通过 ViewModel 来实现消息总线更优雅（参考UserViewModel）
         * 这边纯粹为以下知识点服务，为用而用：
         * SharedFlowBus 消息总线
         */
        DatabaseHelper.registerUIMode(this) { eventBean ->
            if (eventBean.key == DatabaseHelper.UI_MODE) {
                when (eventBean.value) {
                    "1" -> {
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
                        QbSdk.unForceSysWebView()
                    }
                    "2" -> {
                        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
                        QbSdk.forceSysWebView()
                    }
                    else -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
                }
            }
        }
        DatabaseHelper.getUIMode()
        Thread {
            //X5内核初始化
            val map = HashMap<String, Any>()
            map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
            map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
            QbSdk.initTbsSettings(map)
            QbSdk.initX5Environment(applicationContext, object : QbSdk.PreInitCallback {
                override fun onViewInitFinished(arg0: Boolean) {}

                override fun onCoreInitFinished() {}
            })
        }.start()
        //WebView预加载
//        WebViewManager.prepare(applicationContext)
    }

    override fun onDestroy() {
        super.onDestroy()
        DatabaseHelper.close()
        WebViewManager.destroy()
    }

    override fun setContentView(view: View) {
        super.setContentView(view)
        val navHostFragment = supportFragmentManager.findFragmentById(controllerId())
        navController = (navHostFragment as NavHostFragment).navController
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (System.currentTimeMillis() - exitTime > 2000) {
                    exitTime = System.currentTimeMillis()
                    val msg = getString(R.string.one_more_press_2_back)
                    Toast.makeText(this@RouterActivity, msg, Toast.LENGTH_SHORT).show()
                } else {
                    moveTaskToBack(true)
                }
            }
        })
    }

    fun navigate(@IdRes resId: Int, args: Bundle? = null) {
        navController.navigate(
            resId, args, NavOptions.Builder()
                .setEnterAnim(R.anim.slide_in_right)
                .setExitAnim(R.anim.slide_out_left)
                .setPopEnterAnim(R.anim.slide_in_left)
                .setPopExitAnim(R.anim.slide_out_right)
                .build()
        )
    }

    /**
     * 通过正则匹配“{}”内的参数并替换
     */
    fun navigate(deepLink: String, args: Bundle? = null) {
        var newDeepLink = "http://fragment.haiheng.com/$deepLink"
        args?.apply {
            val matcher = Pattern.compile("(\\{)(.+?)(\\})").matcher(newDeepLink)
            while (matcher.find()) {
                val key = matcher.group(2)
                LogUtils.e("navigate  key:${key}")
                if (containsKey(key)) {
                    newDeepLink = newDeepLink.replace("{$key}", get(key).toString())
                    LogUtils.e("navigate  newDeepLink:${newDeepLink}")
                }
            }
        }
        navController.navigate(
            Uri.parse(newDeepLink), NavOptions.Builder()
                .setEnterAnim(R.anim.slide_in_right)
                .setExitAnim(R.anim.slide_out_left)
                .setPopEnterAnim(R.anim.slide_in_left)
                .setPopExitAnim(R.anim.slide_out_right)
                .build()
        )
    }

    fun navigateUp(){
        navController.navigateUp()
    }

    fun popBackStack(@IdRes destinationId: Int, inclusive: Boolean) {
        navController.popBackStack(destinationId, inclusive)
    }

    /**
     * 网络请求结果处理（不建议封装在网络请求框架中）
     */
    fun <T : HttpResponse> httpParseSuccess(result: T, success: ((T) -> Unit)) {
        when (result.errorCode) {
            "0" -> success.invoke(result)
//            "-1001" -> navigation(RourePage.LOGIN_CARD)
            else -> showTips(result.errorMsg)
        }
    }

    override fun getResources(): Resources {
        //需要升级到 v1.1.2 及以上版本才能使用 AutoSizeCompat
        lifecycleScope.launch(Dispatchers.Main) {
            AutoSizeCompat.autoConvertDensityOfGlobal(super.getResources());//如果没有自定义需求用这个方法
        }
        return super.getResources()

    }


}